package br.com.jk.valealim.cartaovenda;

import br.com.jk.master.MasterSt;
import br.com.jk.util.DAOException;
import br.com.jk.util.RNException;
import br.com.jk.valealim.cartaotipo.*;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.JOptionPane;
import br.com.jk.util.Util;
import br.com.jk.valealim.cartao.Cartao;
import br.com.jk.valealim.cartao.CartaoJDialog;
import br.com.jk.valealim.cartao.CartaoRn;
import java.awt.Frame;
import java.math.BigDecimal;
import java.util.Date;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import net.sf.jasperreports.engine.JRException;
import org.hibernate.PropertyValueException;

/**
 *
 * @author Camilo
 */
public class CartaoVendaJDialog extends javax.swing.JDialog {

  private static CartaoVendaJDialog cartaoVendaJDialog;
  // Model da tabela
  CartaoVendaTableModel cartaoTM = new CartaoVendaTableModel();
  List<CartaoVenda> lstCartao;
  private Boolean modoConsulta = false;
  private int colunaSel;
  private Cartao cartao;

  public static CartaoVendaJDialog getInstance(Frame parent, boolean modal) {
    if (cartaoVendaJDialog == null) {
      cartaoVendaJDialog = new CartaoVendaJDialog(parent, modal);
    }
    return cartaoVendaJDialog;
  }

  /**
   * Creates new form CartaoTipoJDialog
   */
  private CartaoVendaJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    setLocationRelativeTo(null);
    jlFiltro.setVisible(false);
    jtfIdCartao.requestFocus();
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do
   * NOT modify this code. The content of this method is always regenerated by the Form
   * Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    JtbMaster = new javax.swing.JToolBar();
    JbNovo = new javax.swing.JButton();
    JbSalvar = new javax.swing.JButton();
    JbEditar = new javax.swing.JButton();
    JbCancelar = new javax.swing.JButton();
    JbExcluir = new javax.swing.JButton();
    JbPesquisar = new javax.swing.JButton();
    JbRelatorio = new javax.swing.JButton();
    jSeparator1 = new javax.swing.JToolBar.Separator();
    JbRefresh = new javax.swing.JButton();
    jlFiltro = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jtCartaoVenda = new javax.swing.JTable();
    jpDados = new javax.swing.JPanel();
    jLabel2 = new javax.swing.JLabel();
    jtfId = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jtfCupom = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    jLabel12 = new javax.swing.JLabel();
    jLabel10 = new javax.swing.JLabel();
    jLabel11 = new javax.swing.JLabel();
    jtfAutorizacao = new javax.swing.JTextField();
    jbReiniciar = new javax.swing.JButton();
    jftfDataCupom = new javax.swing.JFormattedTextField();
    jftfDataAutorizacao = new javax.swing.JFormattedTextField();
    jftfPlano = new javax.swing.JFormattedTextField();
    jtfValor = new javax.swing.JTextField();
    jpDados1 = new javax.swing.JPanel();
    jLabel6 = new javax.swing.JLabel();
    jtfIdCartao = new javax.swing.JTextField();
    jLabel7 = new javax.swing.JLabel();
    jtfCartaoNum = new javax.swing.JTextField();
    jLabel8 = new javax.swing.JLabel();
    jtfCliente = new javax.swing.JTextField();
    jtfTipoCartao = new javax.swing.JTextField();
    jLabel13 = new javax.swing.JLabel();
    jtfCodVerif = new javax.swing.JTextField();
    jLabel9 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Lançamento das vendas");
    setResizable(false);

    JtbMaster.setRollover(true);

    JbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-new.png"))); // NOI18N
    JbNovo.setToolTipText("Novo Registro");
    JbNovo.setEnabled(false);
    JbNovo.setFocusable(false);
    JbNovo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbNovo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbNovo.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbNovoActionPerformed(evt);
      }
    });
    JtbMaster.add(JbNovo);

    JbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-save-hd.png"))); // NOI18N
    JbSalvar.setToolTipText("Salvar Registro");
    JbSalvar.setEnabled(false);
    JbSalvar.setFocusable(false);
    JbSalvar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbSalvar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbSalvar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbSalvarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbSalvar);

    JbEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-edit.png"))); // NOI18N
    JbEditar.setToolTipText("Alterar registro");
    JbEditar.setEnabled(false);
    JbEditar.setFocusable(false);
    JbEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbEditar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbEditarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbEditar);

    JbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/dialog-cancel.png"))); // NOI18N
    JbCancelar.setToolTipText("Cancelar o procedimento");
    JbCancelar.setEnabled(false);
    JbCancelar.setFocusable(false);
    JbCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbCancelar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbCancelarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbCancelar);

    JbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/archive-remove.png"))); // NOI18N
    JbExcluir.setToolTipText("Excluir o registro");
    JbExcluir.setEnabled(false);
    JbExcluir.setFocusable(false);
    JbExcluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbExcluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbExcluir.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbExcluirActionPerformed(evt);
      }
    });
    JtbMaster.add(JbExcluir);

    JbPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/edit-find.png"))); // NOI18N
    JbPesquisar.setToolTipText("PESQUISA. (Space)");
    JbPesquisar.setEnabled(false);
    JbPesquisar.setFocusable(false);
    JbPesquisar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbPesquisar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbPesquisar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbPesquisarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbPesquisar);

    JbRelatorio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/report.png"))); // NOI18N
    JbRelatorio.setToolTipText("Relatórios");
    JbRelatorio.setFocusable(false);
    JbRelatorio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRelatorio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRelatorio.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRelatorioActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRelatorio);
    JtbMaster.add(jSeparator1);

    JbRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-refresh.png"))); // NOI18N
    JbRefresh.setToolTipText("Atualizar registros da lista");
    JbRefresh.setEnabled(false);
    JbRefresh.setFocusable(false);
    JbRefresh.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRefresh.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRefresh.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRefreshActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRefresh);

    jlFiltro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/task-attempt.png"))); // NOI18N
    jlFiltro.setToolTipText("FILTRO ATIVO. Clique no botão Atualizar para restaurar");
    JtbMaster.add(jlFiltro);

    jtCartaoVenda.setModel(cartaoTM);
    jtCartaoVenda.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtCartaoVenda.getSelectedRow();
        selecionado();
      }
    });

    jtCartaoVenda.getColumnModel().getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtCartaoVenda.getSelectedColumn();
        selecionado();
      }
    });
    jtCartaoVenda.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    jtCartaoVenda.getColumnModel().getColumn(CartaoVendaTableModel.COLUMN_COD_DATA_AUTORIZACAO).setPreferredWidth(90);
    jtCartaoVenda.getColumnModel().getColumn(CartaoVendaTableModel.COLUMN_COD_DATA_CUPOM).setPreferredWidth(88);
    jtCartaoVenda.getColumnModel().getColumn(CartaoVendaTableModel.COLUMN_COD_PLANO).setPreferredWidth(50);
    jtCartaoVenda.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        jtCartaoVendaMouseClicked(evt);
      }
    });
    jtCartaoVenda.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtCartaoVendaKeyPressed(evt);
      }
    });
    jScrollPane1.setViewportView(jtCartaoVenda);

    jpDados.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Dados"));

    jLabel2.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel2.setText("Id");

    jtfId.setEditable(false);
    jtfId.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfId.setEnabled(false);

    jLabel1.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel1.setText("Nº Cupom");

    jtfCupom.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfCupom.setEnabled(false);
    jtfCupom.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jtfCupomFocusGained(evt);
      }
    });
    jtfCupom.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfCupomKeyPressed(evt);
      }
    });

    jLabel3.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel3.setText("Data Cupom");

    jLabel4.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel4.setText("Valor");

    jLabel12.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel12.setText("Plano");

    jLabel10.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel10.setText("Data Aut.");

    jLabel11.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel11.setText("Autorização");

    jtfAutorizacao.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jtfAutorizacao.setEnabled(false);
    jtfAutorizacao.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jtfAutorizacaoFocusGained(evt);
      }
    });
    jtfAutorizacao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfAutorizacaoKeyPressed(evt);
      }
    });

    jbReiniciar.setFont(new java.awt.Font("Liberation Sans", 1, 14)); // NOI18N
    jbReiniciar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/edit-undo.png"))); // NOI18N
    jbReiniciar.setMnemonic('r');
    jbReiniciar.setText("Reiniciar");
    jbReiniciar.setToolTipText("Cancela todas as transações atuais e habilita a pesquisa de um novo cartão.");
    jbReiniciar.setEnabled(false);
    jbReiniciar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbReiniciarActionPerformed(evt);
      }
    });

    try {
      jftfDataCupom.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
    } catch (java.text.ParseException ex) {
      ex.printStackTrace();
    }
    jftfDataCupom.setEnabled(false);
    jftfDataCupom.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jftfDataCupom.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jftfDataCupomFocusGained(evt);
      }
    });
    jftfDataCupom.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jftfDataCupomKeyPressed(evt);
      }
    });

    try {
      jftfDataAutorizacao.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
    } catch (java.text.ParseException ex) {
      ex.printStackTrace();
    }
    jftfDataAutorizacao.setEnabled(false);
    jftfDataAutorizacao.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jftfDataAutorizacao.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jftfDataAutorizacaoFocusGained(evt);
      }
      public void focusLost(java.awt.event.FocusEvent evt) {
        jftfDataAutorizacaoFocusLost(evt);
      }
    });
    jftfDataAutorizacao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jftfDataAutorizacaoKeyPressed(evt);
      }
    });

    try {
      jftfPlano.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("U")));
    } catch (java.text.ParseException ex) {
      ex.printStackTrace();
    }
    jftfPlano.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jftfPlano.setEnabled(false);
    jftfPlano.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jftfPlano.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jftfPlanoFocusGained(evt);
      }
    });
    jftfPlano.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jftfPlanoKeyPressed(evt);
      }
    });

    jtfValor.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jtfValor.setEnabled(false);
    jtfValor.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jtfValorFocusGained(evt);
      }
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfValorFocusLost(evt);
      }
    });
    jtfValor.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfValorKeyPressed(evt);
      }
    });

    javax.swing.GroupLayout jpDadosLayout = new javax.swing.GroupLayout(jpDados);
    jpDados.setLayout(jpDadosLayout);
    jpDadosLayout.setHorizontalGroup(
      jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jpDadosLayout.createSequentialGroup()
        .addContainerGap()
        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(jpDadosLayout.createSequentialGroup()
            .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel10)
              .addComponent(jftfDataAutorizacao, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
              .addGroup(jpDadosLayout.createSequentialGroup()
                .addComponent(jLabel12)
                .addGap(36, 36, 36))
              .addGroup(jpDadosLayout.createSequentialGroup()
                .addComponent(jftfPlano)
                .addGap(19, 19, 19)))
            .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(jpDadosLayout.createSequentialGroup()
                .addComponent(jLabel11)
                .addContainerGap())
              .addGroup(jpDadosLayout.createSequentialGroup()
                .addComponent(jtfAutorizacao, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jbReiniciar))))
          .addGroup(jpDadosLayout.createSequentialGroup()
            .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
              .addComponent(jLabel2)
              .addComponent(jtfId, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel1)
              .addComponent(jtfCupom, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel3)
              .addComponent(jftfDataCupom, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel4)
              .addComponent(jtfValor, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(0, 0, Short.MAX_VALUE))))
    );
    jpDadosLayout.setVerticalGroup(
      jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jpDadosLayout.createSequentialGroup()
        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel2)
          .addComponent(jLabel1)
          .addComponent(jLabel3)
          .addComponent(jLabel4))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jtfId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfCupom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jftfDataCupom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
          .addGroup(jpDadosLayout.createSequentialGroup()
            .addComponent(jLabel12)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(jftfDataAutorizacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(jftfPlano, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(jtfAutorizacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
          .addGroup(jpDadosLayout.createSequentialGroup()
            .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
              .addComponent(jLabel10)
              .addComponent(jLabel11))
            .addGap(31, 31, 31))))
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpDadosLayout.createSequentialGroup()
        .addGap(0, 0, Short.MAX_VALUE)
        .addComponent(jbReiniciar))
    );

    jpDados1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Dados do Cartão"));

    jLabel6.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jLabel6.setText("Id Cartão");

    jtfIdCartao.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jtfIdCartao.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jtfIdCartao.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jtfIdCartaoFocusGained(evt);
      }
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfIdCartaoFocusLost(evt);
      }
    });
    jtfIdCartao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdCartaoKeyPressed(evt);
      }
    });

    jLabel7.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jLabel7.setText("Nº Cartão");

    jtfCartaoNum.setEditable(false);
    jtfCartaoNum.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jtfCartaoNum.setHorizontalAlignment(javax.swing.JTextField.CENTER);

    jLabel8.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jLabel8.setText("Nome do Cliente");

    jtfCliente.setEditable(false);
    jtfCliente.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jtfCliente.setHorizontalAlignment(javax.swing.JTextField.CENTER);

    jtfTipoCartao.setEditable(false);
    jtfTipoCartao.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jtfTipoCartao.setHorizontalAlignment(javax.swing.JTextField.CENTER);

    jLabel13.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jLabel13.setText("Cod Verif");

    jtfCodVerif.setEditable(false);
    jtfCodVerif.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jtfCodVerif.setHorizontalAlignment(javax.swing.JTextField.CENTER);

    jLabel9.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jLabel9.setText("Tipo Cartão");

    javax.swing.GroupLayout jpDados1Layout = new javax.swing.GroupLayout(jpDados1);
    jpDados1.setLayout(jpDados1Layout);
    jpDados1Layout.setHorizontalGroup(
      jpDados1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jpDados1Layout.createSequentialGroup()
        .addGroup(jpDados1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(jLabel8)
          .addGroup(jpDados1Layout.createSequentialGroup()
            .addGroup(jpDados1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jtfIdCartao, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(jLabel6))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jpDados1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel9)
              .addComponent(jtfTipoCartao, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jpDados1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel7)
              .addComponent(jtfCartaoNum, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jpDados1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel13)
              .addComponent(jtfCodVerif, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
          .addComponent(jtfCliente))
        .addContainerGap(16, Short.MAX_VALUE))
    );
    jpDados1Layout.setVerticalGroup(
      jpDados1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jpDados1Layout.createSequentialGroup()
        .addGroup(jpDados1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel6)
          .addComponent(jLabel7)
          .addComponent(jLabel13)
          .addComponent(jLabel9))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jpDados1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jtfIdCartao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfCartaoNum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfTipoCartao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfCodVerif, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(6, 6, 6)
        .addComponent(jLabel8)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jtfCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(JtbMaster, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
          .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jpDados1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
          .addComponent(jpDados, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(JtbMaster, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jpDados1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jpDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void JbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbNovoActionPerformed
    novo();
  }//GEN-LAST:event_JbNovoActionPerformed

  private void JbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbSalvarActionPerformed
    salvar();
  }//GEN-LAST:event_JbSalvarActionPerformed

  private void JbEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbEditarActionPerformed
    editar();
  }//GEN-LAST:event_JbEditarActionPerformed

  private void JbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbCancelarActionPerformed
    cancelar();
  }//GEN-LAST:event_JbCancelarActionPerformed

  private void JbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbExcluirActionPerformed
    excluir();
  }//GEN-LAST:event_JbExcluirActionPerformed

  private void JbPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbPesquisarActionPerformed
    pesquisar();
  }//GEN-LAST:event_JbPesquisarActionPerformed

  private void JbRelatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRelatorioActionPerformed
    try {
      ThreadReport thReport = new ThreadReport();
      thReport.start();
    } catch (Exception e) {
      Util.msgErro(e, "Erro ao gerar o relatório");
    }
  }//GEN-LAST:event_JbRelatorioActionPerformed

  private void JbRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRefreshActionPerformed
    listar(cartao);
    jlFiltro.setVisible(false);
    JbPesquisar.setEnabled(false);
  }//GEN-LAST:event_JbRefreshActionPerformed

  private void jtCartaoVendaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtCartaoVendaMouseClicked
    if (cartaoTM.getRowCount() > 0 && (jtfId.getText() != null && jtfValor != null)) {
      habilitaJb(true, false, true, false, true);
      habilitaJtf(false);
      limpar();
      modoConsulta = false;
      selecionado();
    }
  }//GEN-LAST:event_jtCartaoVendaMouseClicked

  private void jtCartaoVendaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtCartaoVendaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
      if (modoConsulta) {
        this.pesquisar();
      }
    }
  }//GEN-LAST:event_jtCartaoVendaKeyPressed

  private void jtfCupomKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCupomKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jftfDataCupom.requestFocus();
    }
  }//GEN-LAST:event_jtfCupomKeyPressed

  private void jtfIdCartaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdCartaoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfIdCartao.getText().isEmpty()) {
        consultaCartao();
      } else {
        habilitaEdicao(Integer.parseInt(jtfIdCartao.getText()));
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      consultaCartao();
    }
  }//GEN-LAST:event_jtfIdCartaoKeyPressed

  private void jtfAutorizacaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfAutorizacaoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      this.salvar();
    }
  }//GEN-LAST:event_jtfAutorizacaoKeyPressed

  private void jbReiniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbReiniciarActionPerformed
    reiniciar();
  }//GEN-LAST:event_jbReiniciarActionPerformed

  private void jftfDataCupomKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jftfDataCupomKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfValor.requestFocus();
    }
  }//GEN-LAST:event_jftfDataCupomKeyPressed

  private void jftfDataAutorizacaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jftfDataAutorizacaoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jftfPlano.requestFocus();
    }
  }//GEN-LAST:event_jftfDataAutorizacaoKeyPressed

  private void jftfPlanoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jftfPlanoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfAutorizacao.requestFocus();
    }
  }//GEN-LAST:event_jftfPlanoKeyPressed

  private void jtfValorFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfValorFocusLost
//    jtfValor.setText(Moeda.mascaraDinheiro(Double.parseDouble(jtfValor.getText()), Moeda.DINHEIRO_REAL));
    jtfValor.setText(jtfValor.getText().replaceAll(",", "."));
  }//GEN-LAST:event_jtfValorFocusLost

  private void jtfValorKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfValorKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jftfDataAutorizacao.isEnabled()) {
        jftfDataAutorizacao.requestFocus();
      } else {
        this.salvar();
      }
    }
  }//GEN-LAST:event_jtfValorKeyPressed

  private void jtfIdCartaoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfIdCartaoFocusGained
    MasterSt.setJlStatusMessage("Pressione Enter ou F12 (Pesquisa) para continuar.");
  }//GEN-LAST:event_jtfIdCartaoFocusGained

  private void jtfCupomFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfCupomFocusGained
    MasterSt.setJlStatusMessage("Digite o nº do cupom fiscal referente essa venda.");
  }//GEN-LAST:event_jtfCupomFocusGained

  private void jftfDataCupomFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jftfDataCupomFocusGained
    MasterSt.setJlStatusMessage("Digite a data do cupom fiscal.");
  }//GEN-LAST:event_jftfDataCupomFocusGained

  private void jtfValorFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfValorFocusGained
    MasterSt.setJlStatusMessage("Digite o valor que será debitado pelo cartão.");
  }//GEN-LAST:event_jtfValorFocusGained

  private void jftfDataAutorizacaoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jftfDataAutorizacaoFocusGained
    MasterSt.setJlStatusMessage("Digite a data em que foi retornada a autorização.");
  }//GEN-LAST:event_jftfDataAutorizacaoFocusGained

  private void jtfAutorizacaoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfAutorizacaoFocusGained
    MasterSt.setJlStatusMessage("Digite o número da autorização");
  }//GEN-LAST:event_jtfAutorizacaoFocusGained

  private void jftfDataAutorizacaoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jftfDataAutorizacaoFocusLost
    MasterSt.setJlStatusNull();
  }//GEN-LAST:event_jftfDataAutorizacaoFocusLost

  private void jftfPlanoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jftfPlanoFocusGained
    MasterSt.setJlStatusNull();
  }//GEN-LAST:event_jftfPlanoFocusGained

  private void jtfIdCartaoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfIdCartaoFocusLost
    MasterSt.setJlStatusNull();
  }//GEN-LAST:event_jtfIdCartaoFocusLost

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(CartaoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(CartaoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(CartaoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(CartaoTipoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        CartaoVendaJDialog dialog = new CartaoVendaJDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton JbCancelar;
  private javax.swing.JButton JbEditar;
  private javax.swing.JButton JbExcluir;
  private javax.swing.JButton JbNovo;
  private javax.swing.JButton JbPesquisar;
  private javax.swing.JButton JbRefresh;
  private javax.swing.JButton JbRelatorio;
  private javax.swing.JButton JbSalvar;
  private javax.swing.JToolBar JtbMaster;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel10;
  private javax.swing.JLabel jLabel11;
  private javax.swing.JLabel jLabel12;
  private javax.swing.JLabel jLabel13;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel6;
  private javax.swing.JLabel jLabel7;
  private javax.swing.JLabel jLabel8;
  private javax.swing.JLabel jLabel9;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JToolBar.Separator jSeparator1;
  private javax.swing.JButton jbReiniciar;
  private javax.swing.JFormattedTextField jftfDataAutorizacao;
  private javax.swing.JFormattedTextField jftfDataCupom;
  private javax.swing.JFormattedTextField jftfPlano;
  private javax.swing.JLabel jlFiltro;
  private javax.swing.JPanel jpDados;
  private javax.swing.JPanel jpDados1;
  private javax.swing.JTable jtCartaoVenda;
  private javax.swing.JTextField jtfAutorizacao;
  private javax.swing.JTextField jtfCartaoNum;
  private javax.swing.JTextField jtfCliente;
  private javax.swing.JTextField jtfCodVerif;
  private javax.swing.JTextField jtfCupom;
  private javax.swing.JTextField jtfId;
  private javax.swing.JTextField jtfIdCartao;
  private javax.swing.JTextField jtfTipoCartao;
  private javax.swing.JTextField jtfValor;
  // End of variables declaration//GEN-END:variables

  private void setJtCartaoTm(List<CartaoVenda> ct) {
    removeAllJtCartaoVenda();
    if (!ct.isEmpty()) {
      cartaoTM.adicionaLista(ct);
    }
  }

  private void setJtCartaoTm(CartaoVenda ct) {
    removeAllJtCartaoVenda();
    if (ct != null) {
      cartaoTM.adiciona(ct);
    }
  }

  private void novo() {
    limpar();
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);
    jtfCupom.requestFocus();
  }

  private void salvar() {
    try {
      CartaoVenda c = criaObjetos();
      CartaoVendaRn ctRn = new CartaoVendaRn();

      //faz a conexão com o bd e salva os registros
      ctRn.salvar(c);

      listar(cartao);
      habilitaJb(true, false, false, false, false);
      habilitaJtf(false);

      if (Util.confirm("Deseja exibir o relatório da última venda?", "Relatório Ult. Venda")
              == Util.SIM) {
        ThreadReport thReport = new ThreadReport();
        thReport.start();
      }
      limpar();

    } catch (IllegalArgumentException | PropertyValueException e) {
      Util.msgErro(e, "Ocorreu erro ao definir os argumentos para gravar "
              + "o registro no banco de dados");
    } catch (DAOException e) {
      Util.msgErro(e, "");
    }
  }

  private void listar(Cartao cartao) {

    CartaoVendaRn ctRn = new CartaoVendaRn();
    setJtCartaoTm(lstCartao = ctRn.listar(cartao));
    MasterSt.setJpbIndeterminate(false);
  }

  private void limpar() {
    jtfId.setText(null);
    jtfCupom.setText(null);
    jftfDataCupom.setText(null);
    jftfDataAutorizacao.setText(null);
    jftfPlano.setText(null);
    jtfValor.setText(null);
    jtfAutorizacao.setText(null);
    MasterSt.setJlStatusNull();
    MasterSt.setJpbIndeterminate(false);
  }

  private void limparCartao() {
    limpar();
    removeAllJtCartaoVenda();
    jtfIdCartao.setText(null);
    jtfTipoCartao.setText(null);
    jtfCartaoNum.setText(null);
    jtfCodVerif.setText(null);
    jtfCliente.setText(null);
    cartao = null;
  }

  private void removeAllJtCartaoVenda() {
    while (cartaoTM.getRowCount() > 0) {
      cartaoTM.remove(0);
    }
  }

  /**
   * Determina quais os botões da barra de ferramentas ficará ativo
   *
   * @param novo
   * @param salvar
   * @param editar
   * @param cancelar
   * @param excluir
   */
  private void habilitaJb(Boolean novo, Boolean salvar, Boolean editar, Boolean cancelar,
          Boolean excluir) {
    JbNovo.setEnabled(novo);
    JbSalvar.setEnabled(salvar);
    JbEditar.setEnabled(editar);
    JbCancelar.setEnabled(cancelar);
    JbExcluir.setEnabled(excluir);
  }

  /**
   * Define se os JTextFields serão liberados para edição do usuário
   *
   * @param tf <b>True</b> - Habilitar; <b>False</b> - Desabilitar;
   */
  private void habilitaJtf(Boolean tf) {
    jtfCupom.setEnabled(tf);
    jftfDataAutorizacao.setEnabled(tf);
    jftfDataCupom.setEnabled(tf);
    jftfPlano.setEnabled(tf);
    jtfValor.setEnabled(tf);
    jtfAutorizacao.setEnabled(tf);
  }

  private void selecionado() {
    int linhaSel = jtCartaoVenda.getSelectedRow();
    String dataformat;
//    verifica se há realmente alguma linha selecionada
    if (linhaSel >= 0) {
      int columSel = jtCartaoVenda.getSelectedColumn();
      boolean pesq = setEnabledPesquisa(columSel);

      jtfId.setText(this.cartaoTM.getValueAt(linhaSel, CartaoVendaTableModel.COLUMN_COD_ID).toString());
      jtfCupom.setText(this.cartaoTM.getValueAt(linhaSel, CartaoVendaTableModel.COLUMN_COD_CUPOMNUM).toString());

      dataformat = Util.formatDataStoS(this.cartaoTM.getValueAt(linhaSel, CartaoVendaTableModel.COLUMN_COD_DATA_CUPOM).toString());
      jftfDataCupom.setText(dataformat);

      dataformat = Util.formatDataStoS(this.cartaoTM.getValueAt(linhaSel, CartaoVendaTableModel.COLUMN_COD_DATA_AUTORIZACAO).toString());
      jftfDataAutorizacao.setText(dataformat);

      jftfPlano.setText(this.cartaoTM.getValueAt(linhaSel, CartaoVendaTableModel.COLUMN_COD_PLANO).toString());
      jtfValor.setText(this.cartaoTM.getValueAt(linhaSel, CartaoVendaTableModel.COLUMN_COD_VALOR_VENDA).toString());
      jtfAutorizacao.setText(this.cartaoTM.getValueAt(linhaSel, CartaoVendaTableModel.COLUMN_COD_AUTORIZACAO).toString());

      modoConsulta = pesq;
      JbPesquisar.setEnabled(pesq);
    }
  }

  private void editar() {
    habilitaJb(false, true, false, true, false);
    jtfCupom.setEnabled(true);
    jftfDataCupom.setEnabled(true);
    jtfValor.setEnabled(true);
    jtfCupom.requestFocus();
  }

  private void excluir() {
//    Define os objetos
    CartaoVendaRn cvRn = new CartaoVendaRn();
    CartaoVenda cv = criaObjetos();
//    Executa o procedimento no BD
    cvRn.excluir(cv);

    listar(cartao);
    limpar();
  }

  /**
   * Cria instâncias dos objetos para serem enviados para o BD
   *
   * @return
   */
  private CartaoVenda criaObjetos() {
    CartaoVenda c = new CartaoVenda();
    if (isNotNull()) {
      //preenche o objeto com os dados dos jtextfield
      if (!jtfId.getText().isEmpty()) {
        c.setId(Integer.parseInt(jtfId.getText()));
      }
      c.setCupomNum(Integer.parseInt(jtfCupom.getText()));
      c.setDataCupom(Util.formatDataSToD(jftfDataCupom.getText()));
      c.setValorVenda(new BigDecimal(jtfValor.getText()));
      c.setDataAutorizacao(Util.formatDataSToD(jftfDataAutorizacao.getText()));
      c.setPlano(jftfPlano.getText());
      c.setAutorizacao(Integer.parseInt(jtfAutorizacao.getText()));

      c.setCartao(cartao);

      return c;
    }
    return c;
  }

  private boolean isNotNull() {
    if (jftfDataCupom.getText().isEmpty()) {
      jftfDataCupom.requestFocus();
      return false;
    } else if (jftfDataAutorizacao.getText().isEmpty()) {
      jftfDataAutorizacao.requestFocus();
      return false;
    } else if (jtfValor.getText().isEmpty()) {
      jtfValor.requestFocus();
      return false;
    } else if (jtfAutorizacao.getText().isEmpty()) {
      jtfAutorizacao.requestFocus();
      return false;
    } else {
      return true;
    }
  }

  private void cancelar() {
    limpar();
    habilitaJb(true, false, false, false, false);
    habilitaJtf(false);
    if (modoConsulta) {
      modoConsulta = false;
    } else {
      listar(cartao);
    }
  }

  private void report() throws JRException, Exception {
    CartaoVendaReport mReport = new CartaoVendaReport();
    mReport.geraReportUltVenda();
  }

  /**
   * Habilita a pesquisa somente para os campos configurados nesse método
   *
   * @param coluna Índice da coluna da qual se deseja efetuar a pesquisa
   * @return Se o campo estiver habilitado permite a pesquisa. O default é: false;
   */
  public boolean setEnabledPesquisa(int coluna) {
    colunaSel = coluna;
    switch (coluna) {
      case CartaoVendaTableModel.COLUMN_COD_ID:
        return true;
      case CartaoVendaTableModel.COLUMN_COD_DATA_CUPOM:
        return true;
      case CartaoVendaTableModel.COLUMN_COD_CUPOMNUM:
        return true;
      case CartaoVendaTableModel.COLUMN_COD_DATA_AUTORIZACAO:
        return true;
      case CartaoVendaTableModel.COLUMN_COD_VALOR_VENDA:
        return true;
      default:
        return false;
    }
  }

  private void pesquisar() {
    if (modoConsulta) {
      String criterio = JOptionPane.showInputDialog(null, "Digite o critério da pesquisa:",
              "Pesquisa", JOptionPane.INFORMATION_MESSAGE);
      if (criterio == null || criterio.isEmpty()) {
        JbPesquisar.setEnabled(false);
      } else {
        limpar();

        CartaoVendaRn ctrn = new CartaoVendaRn();
//        Verifica qual é o tipo de campo e executa a consulta específica

        switch (colunaSel) {
          case CartaoVendaTableModel.COLUMN_COD_ID:
            setJtCartaoTm(ctrn.carregar(Integer.parseInt(criterio), cartao));
            break;
          case CartaoVendaTableModel.COLUMN_COD_DATA_CUPOM:
            Date dataCupom = Util.formatDataSToD(criterio);
            setJtCartaoTm(ctrn.pesquisaPadrao(CartaoVendaDaoHibernate.PROPERTY_DATA_CUPOM, dataCupom, cartao));
            break;
          case CartaoVendaTableModel.COLUMN_COD_DATA_AUTORIZACAO:
            Date dataAut = Util.formatDataSToD(criterio);
            setJtCartaoTm(ctrn.pesquisaPadrao(CartaoVendaDaoHibernate.PROPERTY_DATA_AUTORIZACAO, dataAut, cartao));
            break;
          case CartaoVendaTableModel.COLUMN_COD_CUPOMNUM:
            int i = Integer.parseInt(criterio);
            setJtCartaoTm(ctrn.pesquisaPadrao(CartaoVendaDaoHibernate.PROPERTY_CUPOMNUM, i, cartao));
            break;
          case CartaoVendaTableModel.COLUMN_COD_VALOR_VENDA:
            setJtCartaoTm(ctrn.pesquisaPadrao(CartaoVendaDaoHibernate.PROPERTY_VALOR_VENDA, criterio, cartao));
            break;
        }
        jlFiltro.setVisible(true);
      }
    }
  }

  private void getLarguraJtBanco() {
    int grade;
    int column = cartaoTM.getColumnCount();
    for (int i = 0; i < column; i++) {
      grade = this.jtCartaoVenda.getColumnModel().getColumn(i).getPreferredWidth();
      System.out.println(grade);
    }
  }

  private void consultaCartao() {
    MasterSt.setJlStatusMessage("Para selecionar, clique em uma das linhas da tabela e pressione Enter");
    CartaoJDialog.getInstance(null, true, jtfIdCartao, jtfCliente, jtfTipoCartao, jtfCartaoNum, jtfCodVerif).setVisible(true);
  }

  private void habilitaEdicao(int idCartao) {
    try {
      CartaoRn crn = new CartaoRn();
      cartao = crn.carregar(idCartao);

      if (jtfTipoCartao.getText().isEmpty() || jtfCartaoNum.getText().isEmpty()
              || jtfCliente.getText().isEmpty() || jtfCodVerif.getText().isEmpty()) {
        jtfTipoCartao.setText(cartao.getCartaoTipo().getNome());
        jtfCartaoNum.setText(cartao.getCartaoNumero());
        jtfCliente.setText(cartao.getNomeCliente());
        jtfCodVerif.setText(String.valueOf(cartao.getCartaoCodVerif()));
      }

      limpar();
      removeAllJtCartaoVenda();
      listar(cartao);

      JbNovo.setEnabled(true);
      JbRefresh.setEnabled(true);
      jbReiniciar.setEnabled(true);
      jtfIdCartao.setEnabled(false);

      jtCartaoVenda.requestFocus();
    } catch (RNException e) {
      Util.msgErro(e, "");
      limparCartao();
      jtfIdCartao.requestFocus();
    }
  }

  private void reiniciar() {
    habilitaJtf(false);
    habilitaJb(false, false, false, false, false);
    limparCartao();
    JbRefresh.setEnabled(false);
    jbReiniciar.setEnabled(false);
    JbPesquisar.setEnabled(false);
    jlFiltro.setVisible(false);

    jtfIdCartao.setEnabled(true);
    jtfIdCartao.requestFocus();
  }

  class ThreadReport extends Thread {

    @Override
    public void run() {
      try {
        MasterSt.setJpbIndeterminate(true);
        MasterSt.setJlStatusMessage("Gerando o relatório...");

        report();
      } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage());
      }
    }
  }
}
